import Taro from "@tarojs/taro";
import {getRuntime, ServerHost, uploadUrl} from './common';
import {toJS} from "mobx";
import * as api from "../api/api";

// import { reaction } from "mobx";

export class Runtime {
  /**
   *
   * 设置存储
   * @param {any} info
   */
  setStorage = (key: string, value?: object) => {
    Taro.setStorageSync(key, value ? JSON.stringify(value) : "");
  }

  /**
   *
   * 获取存储
   * @returns
   */
  getStorage = (key: string) => {
    var data = Taro.getStorageSync(key);
    if (data) {
      return JSON.parse(data);
    } else {
      return null;
    }
  }

  /**
   *
   * 设置用户信息
   * @param {any} info
   */
  setUserInfo = (info?: any) => {
    Taro.setStorageSync("user", info ? JSON.stringify(info) : "");
  }

  /**
   *
   * 获取用户信息
   * @returns
   */
  getUserInfo = () => {
    var data = Taro.getStorageSync("user");
    if (data) {
      return JSON.parse(data);
    } else {
      return null;
    }
  }

  /**
   * 获取token
   */
  getToken = () => {
    const user = this.getUserInfo();
    if(!user) return ''
    return {Authorization: "Bearer " + (user && user.token || '')};
    // return { Authorization: "Bearer LJ3wfBJIZ43UiiEwgw-pWsOIKNSV07-cDKv8rBCEqEQ3sikovZbiIpI7LeSBwdq278PZWyMrbJe1rr_ZMvwlj3qBORgvjQ2JHsFc5Zb8tWnfpsV7VQi-Nq27fNrM7zBFpWsxow_9FBWNLW9fYqEAmsx86HEePmvBm3Jbpr8O7b08fpV9QzRiR8hWrzeeZMiPRSfJ-NdpqJX2A8UPDG5nwPmSE7dK3-5qcJfGBelP6ROa5-Dy8ion31VZYRmYt8KbOggc9RFy-GPyL8Zp232Si8JdoTJyoW4Gpj9AYmrHrZh8uRGzqawq1GXHMl5Ma712UM4ZX_ThZAglcDL4u5xr_kbb_jTAK38q9zZYD5G8Z_C1rJd2yVby_BS7wyx99y2MFV6249t1I9hqVwJxdFU9PcNux1eyltUNibDGMXLzjLv2EDCIN11O-Y6-x6GmKdkNkzrLlMlhwxuWzzw70n0h_yywBkPFPZPMTodf7stFuEHI_EKHjzb3GgEgmBSI09cE" };
  }

  isLogin = () => {
    if (!localStorage.token) {
      // return false;
      return "请先登录";
    } else {
      return true;
    }
  }

  navigateTo = (url: string, isNeedLogin:boolean = false) => {
    if(!getRuntime().getToken() && isNeedLogin) {
      getRuntime().navigateTo('/pages/login/login'); return
    }
    Taro.navigateTo({
      url: url
    });
  }

  redirectTo = (url: string) => {
    Taro.redirectTo({
      url: url
    });
  }

  navigateBack = () => {
    Taro.navigateBack({
      delta: 1
    });
  }
  switchTab = (url: string) => {
    Taro.switchTab({
      url: url
    })
  }

  pageScrollToTop = () => {
    Taro.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
  }

  pageScrollTo = (scrollTop) => {
    Taro.pageScrollTo({
      scrollTop: scrollTop,
      duration: 300,
    });
  }

  showToast = (title: string, icon?: string) => {
    Taro.showToast({
      title: title,
      icon: icon || 'none',
      mask: true,
    });
  };

  showModal = (title, content:string='', callback: () => void) => {
    Taro.showModal({
      title: title,
      content: content,
    })
      .then(res => {
        if (res.confirm) {
          callback()
        }
      });
  }

  makePhoneCall = (phoneNumber: string) => {
    Taro.makePhoneCall({
      phoneNumber: phoneNumber,
    })
  }

  wxloginout = () => {
    this.setUserInfo();
    Taro.clearStorage();
  };

  wxlogin = (res, getToken: (any) => void, fail: () => void) => {
    const user = this.getUserInfo();
    if (user) return;
    const that = this;
    Taro.login({
      success: function (loginres) {
        if (loginres.code && res.encryptedData) {
          that.setStorage("code", {code: loginres.code});
          const info = {
            code: loginres.code,
            ...res,
          };
          console.log(info);
          getToken(info);
        } else {
          fail();
        }
      }
    });
  };

  getwxcode = (callback: (code: string) => void) => {
    Taro.login({
      success: function (loginres) {
        callback(loginres.code);
      }
    });
  }

  wxauth = (name: string, callback: (auth: boolean) => void) => {
    Taro.getSetting({}).then(res => {
      if (res.authSetting[name]) {
        callback(true);
      } else {
        callback(false);
      }
    }).catch((e) => {
      callback(false);
    })
  }


  upload = (callback, count = 1) => {
    Taro.chooseImage({
      count: count,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera']
    })
      .then(res => {
        console.log(res)
        Taro.showLoading({
          title: '加载中...'
        })
        Taro.uploadFile({
          url: ServerHost + uploadUrl,
          header: this.getToken(),
          filePath: res.tempFilePaths[0],
          name: 'file'
        })
          .then(res1 => {
            Taro.hideLoading()
            if (res1.statusCode == 200) {
              const data = JSON.parse(res1.data);
              if (data.success) {
                callback(data.result);
                // this.setState({ avatar: data.result });
              } else {
                this.showToast(data.error.message, 'none');
              }
            } else {
              this.showToast(res1['errMsg'], 'none');
            }
          });
      });
  }


  upIdCard = (callback, type = 1) => {
    Taro.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album',],
    })
      .then(res => {
        Taro.showLoading({
          title: '加载中...'
        })
        Taro.uploadFile({
          url: ServerHost + uploadUrl,
          header: this.getToken(),
          filePath: res.tempFilePaths[0],
          name: 'file',
        })
          .then(res1 => {
            Taro.hideLoading()
            if (res1.statusCode == 200) {
              const data = JSON.parse(res1.data);
              if (data.success) {
                callback(data.result);
              }
              else {
                this.showToast(data.error.message, 'none');
              }
            }
            else {
              const data = JSON.parse(res1.data);
              this.showToast(data.error.message, 'none');
            }
          });
      });
  }

  /**
   * 图片上传
   * @param files
   * @param callback
   */
  uploadFile = (files: Array<string>, callback: (urls: string[]) => void) => {
    let images = Array<string>();
    for (var i = images.length; i < files.length; i++) {
      const file = files[i]['file']['path'];
      Taro.showLoading({ title: '图片上传中...' })
      Taro.uploadFile({
        url: ServerHost + uploadUrl,
        header: this.getToken(),
        filePath: file,
        name: 'file'
      })
        .then(res1 => {
          Taro.hideLoading()
          if (res1.statusCode == 200) {
            const data = JSON.parse(res1.data);
            if (data.success) {
              images.push(data.result);
              if (images.length == files.length)
                this.showToast('图片上传成功~')
                callback(images);
            }
            else {
              this.showToast(data.error.message, 'none');
            }
          }
          else {
            this.showToast(res1['errMsg'], 'none');
          }
        }).catch(error => {
          Taro.hideLoading()
          console.log(error)
      })
    }
  }



  //下拉刷新
  pullDownRefresh = (callback) => {
    Taro.showNavigationBarLoading() //在标题栏中显示加载
    callback();
    Taro.hideNavigationBarLoading() //在标题栏中显示加载
    Taro.stopPullDownRefresh();
  }

  createSelectorQuery = (): Taro.SelectorQuery => {
    return Taro.createSelectorQuery();
  }

  scanCode = (callback: (string) => void) => {
    Taro.scanCode().then(res => {
      callback(res.result);
    });
  }

  getLocation = (callback: (latitude, longitude) => void) => {
    Taro.getLocation({
      type: 'wgs84'
    }).then(res => {
      callback(res.latitude, res.longitude);
    });
  }

  chooseLocation = (callback: (name, address, latitude, longitude) => void) => {
    Taro.chooseLocation().then(res => {
      callback(res.name, res.address, res.latitude, res.longitude);
    });
  }

  openLocation = (latitude, longitude) => {
    Taro.openLocation({latitude, longitude});
  }

  wxPay = (payParams, callback: () => void) => {
    const that = this;
    Taro.requestPayment({
      timeStamp: payParams.timeStamp,
      nonceStr: payParams.nonceStr,
      package: payParams.package,
      signType: payParams.signType,
      paySign: payParams.paySign,
      success(res) {
        // console.log(res);
        callback();
      },
      fail(res) {
        console.log(res);
        that.showToast("支付失败");
      }
    })
  }

  isEmpty = (str) => {
    if (typeof str == "undefined" || str == null || str == "") {
      return true;
    } else {
      return false;
    }
  }

  commonPay(orderId: number, custom: number, isPayPoints: boolean = false, callBack) {
      let payUrl = `${ServerHost}/api/Account/PaymentParameters?orderId=${orderId}&custom=${custom}&isPayPoint=${isPayPoints}`
      let user = getRuntime().getUserInfo()
      let token = user && user.token ? 'Bearer ' + user.token : ''
      fetch(payUrl, {
        method: 'GET',
        headers: {'Authorization': token}
      })
      .then(response => response.json())
      .then(response => {
        console.log(response)
        if (response.msg === 'ok') {
          getRuntime().wxPay(response, () => {
            callBack&&callBack()
          })
        } else {
          getRuntime().showToast(response.msgtext);
        }
      })
      .catch(() => {
        getRuntime().showToast('获取支付参数失败~');
      })
  }
}
